<template>
  <div class="orders-container">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="订单ID">
          <el-input v-model="searchForm.ordersId" placeholder="请输入订单ID" />
        </el-form-item>
        <el-form-item label="用户ID">
          <el-input v-model="searchForm.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="支付方式">
          <el-select
            v-model="searchForm.paymentMethod"
            placeholder="请选择支付方式"
            style="width: 150px;"
            clearable
          >
            <el-option
              v-for="item in paymentMethodOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch"
            >搜索</el-button
          >
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 订单表格 -->
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="ordersId" label="订单ID" />
      <el-table-column prop="userId" label="用户ID" />
      <el-table-column prop="totalAmount" label="总金额">
        <template #default="{ row }"> ¥{{ row.totalAmount }} </template>
      </el-table-column>
      <el-table-column prop="paymentMethod" label="支付方式">
        <template #default="{ row }">
          {{
            paymentMethodOptions.find(
              (item) => item.value === row.paymentMethod
            )?.label
          }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column prop="updateTime" label="更新时间" width="180" />
      <!-- <el-table-column label="操作" width="100" fixed="right"> -->
        <!-- <template #default="{ row }"> -->
          <!-- <el-button
            type="primary"
            :icon="Edit"
            circle
            @click="handleEdit(row)"
          /> -->
          <!-- <el-button type="danger" :icon="Delete" circle @click="handleDelete(row.id)" /> -->
        <!-- </template> -->
      <!-- </el-table-column> -->
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 新增/编辑订单对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="80%">
      <el-form :model="orderForm" label-width="100px">
        <el-form-item label="用户ID">
          <el-input v-model="orderForm.userId" />
        </el-form-item>
        <el-form-item label="支付方式">
          <el-select
            v-model="orderForm.paymentMethod"
            placeholder="请选择支付方式"
          >
            <el-option
              v-for="item in paymentMethodOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="orderForm.status" placeholder="请选择订单状态">
            <el-option
              v-for="item in orderStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="订单详情">
          <div class="order-details">
            <div
              v-for="(detail, index) in orderForm.orderDetails"
              :key="detail.id"
              class="detail-item"
            >
              <el-card>
                <template #header>
                  <div class="detail-header">
                    <span>订单详情 #{{ index + 1 }}</span>
                    <el-button
                      type="danger"
                      :icon="Delete"
                      circle
                      @click="removeOrderDetail(index)"
                    />
                  </div>
                </template>
                <el-form-item label="商品ID">
                  <el-input v-model="detail.productId" />
                </el-form-item>
                <el-form-item label="商品标题">
                  <el-input v-model="detail.productTitle" />
                </el-form-item>
                <el-form-item label="SKU参数">
                  <el-input v-model="detail.skuParams" />
                </el-form-item>
                <el-form-item label="SKU值">
                  <el-input v-model="detail.skuValue" />
                </el-form-item>
                <el-form-item label="收货人">
                  <el-input v-model="detail.recipientName" />
                </el-form-item>
                <el-form-item label="收货电话">
                  <el-input v-model="detail.recipientPhone" />
                </el-form-item>
                <el-form-item label="收货地址">
                  <el-input v-model="detail.recipientAddress" type="textarea" />
                </el-form-item>
                <el-form-item label="数量">
                  <el-input-number v-model="detail.quantity" :min="1" />
                </el-form-item>
                <el-form-item label="总价">
                  <el-input v-model="detail.totalPrice" type="number" />
                </el-form-item>
              </el-card>
            </div>
            <el-button type="primary" :icon="Plus" @click="addOrderDetail"
              >添加订单详情</el-button
            >
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Search, Delete, Edit } from "@element-plus/icons-vue";
import { getOrderService } from "@/api/order";

// 支付方式选项
const paymentMethodOptions = [
  { label: "支付宝", value: "支付宝" },
  { label: "微信", value: "微信" },
  { label: "银行卡", value: "银行卡" },
];

// 订单列表数据
const tableData = ref([
  {
    ordersId: 1,
    userId: 1001,
    totalAmount: 299.99,
    paymentMethod: "ALIPAY",
    createTime: "2024-01-01 12:00:00",
    updateTime: "2024-01-01 12:30:00",
  },
]);

// 分页配置
const pagination = ref({
  current: 1,
  size: 10,
  total: 100,
});

// 搜索表单
const searchForm = ref({
  ordersId: null,
  userId: null,
  paymentMethod: null,
  dateRange: [],
});

// 新增/编辑订单对话框
const dialogVisible = ref(false);
const dialogTitle = ref("新增订单");
const isEdit = ref(false);

// 处理分页变化
const handlePageChange = (val) => {
  pagination.value.current = val;
  fetchOrders();
};

// 处理每页显示数量变化
const handleSizeChange = (val) => {
  pagination.value.size = val;
  fetchOrders();
};

// 搜索订单
const handleSearch = () => {
  pagination.value.current = 1;
  fetchOrders();
};

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    ordersId: null,
    userId: null,
    status: null,
    paymentMethod: null,
    dateRange: [],
  };
  fetchOrders();
};

// 打开新增订单对话框
const handleAdd = () => {
  dialogTitle.value = "新增订单";
  isEdit.value = false;
  orderForm.value = {
    userId: "",
    totalAmount: 0,
    paymentMethod: "",
    status: "PENDING_PAYMENT",
    orderDetails: [],
  };
  dialogVisible.value = true;
};

// 打开编辑订单对话框
const handleEdit = (row) => {
  dialogTitle.value = "编辑订单";
  isEdit.value = true;
  orderForm.value = JSON.parse(JSON.stringify(row));
  dialogVisible.value = true;
};

// 删除订单
const handleDelete = (id) => {
  ElMessageBox.confirm("确定要删除该订单吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      // 这里添加删除订单的接口调用
      ElMessage.success("删除成功");
      fetchOrders();
    })
    .catch(() => {});
};

// 添加订单详情
const addOrderDetail = () => {
  orderForm.value.orderDetails.push({
    id: Date.now(),
    productId: "",
    productTitle: "",
    productImage: "",
    skuParams: "",
    skuValue: "",
    recipientName: "",
    recipientPhone: "",
    recipientAddress: "",
    quantity: 1,
    totalPrice: 0,
  });
};

// 删除订单详情
const removeOrderDetail = (index) => {
  orderForm.value.orderDetails.splice(index, 1);
};

// 提交表单
const submitForm = () => {
  // 这里添加新增/编辑订单的接口调用
  dialogVisible.value = false;
  fetchOrders();
};

/**
 * 获取订单列表
 * */
const fetchOrders = async () => {
  const params = {
    ordersId: searchForm.value.ordersId == "" || null,
    userId: searchForm.value.userId, // 注意：这里可能需要根据实际字段调整
    paymentMethod: searchForm.value.paymentMethod,
    startTime: searchForm.value.dateRange[0],
    endTime: searchForm.value.dateRange[1],

    current: pagination.value.current,
    size: pagination.value.size,
    total: pagination.value.total,
  };
  // 调用获取订单列表的接口
  let result = await getOrderService(params);
  tableData.value = result.data?.records || [];
  pagination.value.size = result.data?.size || 10;
  pagination.value.current = result.data?.current || 1;
  pagination.value.total = result.data?.total || 0;
};

onMounted(() => {
  fetchOrders();
});
</script>

<style scoped>
.orders-container {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
}

.search-area {
  margin-bottom: 20px;
}

.toolbar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.order-details {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.detail-item {
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.el-card__header) {
  padding: 10px 20px;
}

:deep(.el-card__body) {
  padding: 20px;
}

/* 美化搜索区域 */
.search-area {
  background: white;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

/* 工具栏样式 */
.toolbar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style> 